import '../models/wiki_config.dart';
import '../models/favorite.dart';
import '../models/browse_history.dart';
import '../providers/wiki_api_provider.dart';
import '../services/config_service.dart';
import '../services/search_service.dart';
import '../services/database_service.dart';

/// Wiki数据仓库 - 管理wiki数据和业务逻辑
/// Wiki Repository - Manages wiki data and business logic
class WikiRepository {
  final WikiApiProvider _apiProvider = WikiApiProvider();
  final ConfigService _configService = ConfigService();
  final SearchService _searchService = SearchService();
  final DatabaseService _databaseService = DatabaseService();

  // ==================== Wiki站点管理 Wiki Sites Management ====================

  /// 获取所有可用的wiki站点 Get all available wiki sites
  Future<List<WikiItem>> getAllWikiSites({
    String? category,
  }) async {
    try {
      return await _searchService.getAllWikis(
        category: category,
      );
    } catch (e) {
      throw Exception('Repository: Failed to get wiki sites - $e');
    }
  }

  /// 搜索wiki站点 Search wiki sites
  Future<List<WikiItem>> searchWikiSites({
    required String query,
    String? category,
  }) async {
    try {
      if (query.trim().isEmpty) {
        return await getAllWikiSites(
          category: category,
        );
      }
      return await _searchService.searchWikis(
        query: query,
        category: category,
      );
    } catch (e) {
      throw Exception('Repository: Failed to search wiki sites - $e');
    }
  }

  /// 根据分类获取wiki站点 Get wiki sites by category
  Future<List<WikiItem>> getWikiSitesByCategory(String category) async {
    try {
      return await _searchService.getWikisByCategory(category);
    } catch (e) {
      throw Exception('Repository: Failed to get wiki sites by category - $e');
    }
  }

  /// 根据ID获取wiki站点 Get wiki site by ID
  Future<WikiItem?> getWikiSiteById(String id) async {
    try {
      return await _searchService.getWikiById(id);
    } catch (e) {
      return null;
    }
  }

  /// 获取所有可用分类 Get all available categories
  Future<List<String>> getAllCategories() async {
    try {
      return await _searchService.getAllCategories();
    } catch (e) {
      throw Exception('Repository: Failed to get categories - $e');
    }
  }

  /// 获取热门wiki站点 Get popular wiki sites
  Future<List<WikiItem>> getPopularWikiSites({int limit = 10}) async {
    try {
      return await _searchService.getPopularWikis(limit: limit);
    } catch (e) {
      throw Exception('Repository: Failed to get popular wiki sites - $e');
    }
  }

  /// 获取搜索建议 Get search suggestions
  Future<List<String>> getSearchSuggestions(String query) async {
    try {
      return await _searchService.getSearchSuggestions(query);
    } catch (e) {
      return [];
    }
  }

  // ==================== 配置管理 Configuration Management ====================

  /// 刷新配置 Refresh configuration
  Future<void> refreshConfig({bool forceRefresh = false}) async {
    try {
      await _configService.getWikiConfig(forceRefresh: forceRefresh);
    } catch (e) {
      throw Exception('Repository: Failed to refresh config - $e');
    }
  }

  /// 检查配置更新 Check for configuration updates
  Future<bool> hasConfigUpdates() async {
    try {
      return await _configService.hasUpdates();
    } catch (e) {
      return false;
    }
  }

  /// 获取配置缓存信息 Get configuration cache info
  Future<Map<String, dynamic>> getConfigCacheInfo() async {
    try {
      return await _configService.getCacheInfo();
    } catch (e) {
      return {};
    }
  }

  // ==================== 收藏管理 Favorites Management ====================

  /// 添加收藏 Add favorite
  Future<bool> addFavorite({
    required String wikiId,
    required String wikiName,
    required String wikiUrl,
    required String title,
    String description = '',
    String iconUrl = '',
  }) async {
    try {
      final favorite = Favorite(
        wikiId: wikiId,
        wikiName: wikiName,
        wikiUrl: wikiUrl,
        title: title,
        description: description,
        iconUrl: iconUrl,
        createdAt: DateTime.now(),
      );
      
      final result = await _databaseService.addFavorite(favorite);
      return result > 0;
    } catch (e) {
      return false;
    }
  }

  /// 删除收藏 Remove favorite
  Future<bool> removeFavorite(String wikiId, String wikiUrl) async {
    try {
      final result = await _databaseService.removeFavorite(wikiId, wikiUrl);
      return result > 0;
    } catch (e) {
      return false;
    }
  }

  /// 获取所有收藏 Get all favorites
  Future<List<Favorite>> getAllFavorites() async {
    try {
      return await _databaseService.getAllFavorites();
    } catch (e) {
      return [];
    }
  }

  /// 检查是否已收藏 Check if favorited
  Future<bool> isFavorited(String wikiId, String wikiUrl) async {
    try {
      return await _databaseService.isFavorited(wikiId, wikiUrl);
    } catch (e) {
      return false;
    }
  }

  /// 根据Wiki ID获取收藏 Get favorites by wiki ID
  Future<List<Favorite>> getFavoritesByWikiId(String wikiId) async {
    try {
      return await _databaseService.getFavoritesByWikiId(wikiId);
    } catch (e) {
      return [];
    }
  }

  // ==================== 浏览历史管理 Browse History Management ====================

  /// 添加浏览历史 Add browse history
  Future<bool> addBrowseHistory({
    required String wikiId,
    required String wikiName,
    required String wikiUrl,
    required String title,
    String description = '',
    String iconUrl = '',
  }) async {
    try {
      final history = BrowseHistory(
        wikiId: wikiId,
        wikiName: wikiName,
        wikiUrl: wikiUrl,
        title: title,
        description: description,
        iconUrl: iconUrl,
        createdAt: DateTime.now(),
        lastVisitAt: DateTime.now(),
      );
      
      final result = await _databaseService.addOrUpdateHistory(history);
      return result > 0;
    } catch (e) {
      return false;
    }
  }

  /// 获取浏览历史 Get browse history
  Future<List<BrowseHistory>> getBrowseHistory({int limit = 50}) async {
    try {
      return await _databaseService.getBrowseHistory(limit: limit);
    } catch (e) {
      return [];
    }
  }

  /// 获取热门浏览记录 Get popular browse records
  Future<List<BrowseHistory>> getPopularHistory({int limit = 10}) async {
    try {
      return await _databaseService.getPopularHistory(limit: limit);
    } catch (e) {
      return [];
    }
  }

  /// 清除浏览历史 Clear browse history
  Future<bool> clearBrowseHistory() async {
    try {
      final result = await _databaseService.clearBrowseHistory();
      return result > 0;
    } catch (e) {
      return false;
    }
  }

  /// 删除指定浏览历史 Delete specific browse history
  Future<bool> deleteBrowseHistory(int id) async {
    try {
      final result = await _databaseService.deleteBrowseHistory(id);
      return result > 0;
    } catch (e) {
      return false;
    }
  }

  // ==================== Wiki内容管理 Wiki Content Management ====================

  /// 获取wiki内容 Get wiki content
  Future<String> getWikiContent(String wikiId, String pageUrl) async {
    try {
      return await _apiProvider.getWikiContent(wikiId, pageUrl);
    } catch (e) {
      throw Exception('Repository: Failed to get wiki content - $e');
    }
  }

  // ==================== 兼容性方法 Compatibility Methods ====================

  /// 兼容旧版本的搜索方法 Legacy search method for compatibility
  Future<List<WikiItem>> searchWikiSitesLegacy(String query) async {
    return await searchWikiSites(
      query: query,
    );
  }
}

